<template>
  <div>

    <div v-show="chartShow" class="chart" id="chart24hrsHistoryUsageStatistics"></div>

    <div v-show="!chartShow" class="chart-warn">本区域暂无历史电费统计</div>
  </div>

</template>

<script>
import * as echarts from "echarts";
import { config } from "./config";
import { block_dic } from "../../common/block_parser";
import { building_map } from "../../common/building_mapper";

function add0(m) {
  return m < 10 ? "0" + m : m;
}

function format(ts) {
  let time = new Date(ts);
  let y = time.getFullYear();
  let m = time.getMonth() + 1;
  let d = time.getDate();
  let h = time.getHours();
  let mm = time.getMinutes();
  let s = time.getSeconds();
  return y + "-" + add0(m) + "-" + add0(d) + " " + add0(h) + ":" + add0(mm) + ":" + add0(s);
}


export default {
  name: "chart-24hrs-history-usage-statistics",


  mounted: function() {
    console.log("block_dic", block_dic, building_map);

    this.getDayRangeByUpdateTime().then(dayRange => {
      console.log("dayRange", dayRange);

      /* TODO 这里应当再包一层Promise 但是时间有限 项目截至 就先这么搞一下 待优化 */
      setTimeout(() => {
        let ec = echarts.init(document.getElementById("chart24hrsHistoryUsageStatistics"), null, { renderer: "svg" });
        ec.setOption(this.getChartOption(Object.keys(dayRange)));
      }, 5000)


      Object.keys(block_dic).forEach(block => {

          // 浅拷贝
          let tmpDic = Object.assign({}, dayRange);
          let promiseList = [];
          block_dic[block].forEach(building_name => {
            let building_id = parseInt(building_map[building_name]);
            promiseList.push(this.getDataByBuildingId(building_id));
          });
          console.log(block, promiseList);
          Promise.all(promiseList).then(values => {
            console.log(block, "values", promiseList.length, values);
            values.forEach(arr => {
              arr.forEach(obj => {
                // 求和
                tmpDic[obj["time"]] = tmpDic[obj["time"]] + parseFloat(obj["fee"]);
              });
            });

            this.series.push({
              name: block,
              type: "line",
              data: Object.values(tmpDic),
              smooth: true
            })

          }).catch(err => {
            console.log(block, err);

          });
      });
    })

  },

  methods: {
    getDayRangeByUpdateTime: function() {
      return new Promise(resolve => {
        this.$api.updateTime().then(res => {
          let updateTime = res.data.data.updateTime;

          // 生成24小时列表
          updateTime = Date.parse(updateTime);
          let endTime = parseInt(updateTime / 1000 / 3600 + "") * 1000 * 3600;

          let dayRange = [];
          for (let i = 0; i < 24; i++) {
            dayRange.push(format(endTime - i * 1000 * 3600));
          }
          dayRange = dayRange.reverse();
          let dic = {};
          dayRange.forEach(ele => {
            dic[ele] = 0.0;
          });

          resolve(dic);
        });
      });
    },


    getDataByBuildingId: function(buildingId) {
      return new Promise((resolve, reject) => {
        this.$api.dataByBuildingIdNTimeType(buildingId, "day").then(res => {
          let data = eval(res.data.data.data);
          if (data !== null) {
            resolve(data);
          } else {
            console.log(buildingId, "null");
          }
        }).catch((err) => {
          console.log(err, buildingId);
          reject(err);
        });
      });
    },

    getChartOption: function(x) {

      return {

        tooltip: {
          trigger: "axis",
          axisPointer: {
            lineStyle: {
              color: config.chartToolTipAxisColor
            }
          }
        },
        legend: {
          textStyle: {
            color: config.chartLabelColor
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },

        xAxis: {
          type: "category",
          boundaryGap: false,
          data: x,
          axisLine: {
            lineStyle: {
              color: config.chartLabelColor
            }
          }
        },
        yAxis: {
          type: "value",
          axisLine: {
            lineStyle: {
              color: config.chartLabelColor
            }
          },
          splitLine: {
            show: false

          }
        },
        series: this.series
      };


    }
  },

  data() {
    return {
      chartShow: true,  // 表格是否有效
      series: []
    };
  }

};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 600px;
  overflow: visible;
}


#range-selector {
  position: absolute;
  top: 0;
  left: 0;
}
</style>